﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Lilium.Web.Mvc.EntityFilters
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
	public class EntityFilterAttribute : ActionFilterAttribute
	{
		public EntityFilterAttribute(Type filterType)
		{
			if (filterType == null) throw new ArgumentNullException("filterType");

			m_FilterType = filterType;
		}

		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			if (filterContext == null) throw new ArgumentNullException("filterContext");

			var filter = CreateFilter(filterContext);
			var filteringService = filterContext.Controller.GetService<IFilteringService>(true);
			filteringService.AddFilter(filter);
		}

		#region public Type FilterType

		private readonly Type m_FilterType;

		public Type FilterType
		{
			get
			{
				return m_FilterType;
			}
		}

		#endregion

		protected virtual IEntityFilter CreateFilter(ActionExecutingContext filterContext)
		{
			if (filterContext == null) throw new ArgumentNullException("filterContext");
			
			return (IEntityFilter)filterContext.Controller.GetService(FilterType, true);
		}
	}
}